<template>
  <div :id="chartId" :style="style" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { v4 as uuidv4 } from 'uuid';

const props = defineProps({
  // 图表配置项
  options: {
    type: Object,
    required: true
  },
  // 图表尺寸
  style: {
    type: Object,
    default: () => ({ width: '100%', height: '400px' })
  },
  // 图表主题
  theme: {
    type: String,
    default: 'light'
  }
});

const chartId = ref(uuidv4());
const chartInstance = ref(null);

// 初始化图表
const initChart = () => {
  // 销毁已有实例
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  // 创建新实例
  chartInstance.value = echarts.init(document.getElementById(chartId.value), props.theme);
  // 设置配置项
  chartInstance.value.setOption(props.options);
};

// 监听配置项变化
watch(
  () => props.options,
  () => {
    if (chartInstance.value) {
      chartInstance.value.setOption(props.options);
    }
  },
  { deep: true }
);

// 窗口大小变化时重绘
const handleResize = () => {
  chartInstance.value?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chartInstance.value?.dispose();
});
</script>

<style scoped>
.chart-container {
  transition: all 0.3s ease;
}
</style>